<template>
    <div>
        <el-card style="height: 9vh">
            <el-row :gutter="10">
                <el-col :span="6">

                    <el-page-header @back="goBack" content="结算页面">
                    </el-page-header>
                    <!--                    <el-button size="mini" @click="toMyCarts"><span style="font-size: 14px">返回购物车</span>-->
                    <!--                    </el-button>-->
                </el-col>
                <el-col :span="18">
                    <el-steps :active="2" finish-status="success" simple
                              style="background-color: #ffffff;height: 10px">
                        <el-step title="我的购物车"></el-step>
                        <el-step title="填写核对订单"></el-step>
                        <el-step title="成功提交订单"></el-step>
                    </el-steps>
                </el-col>
            </el-row>
        </el-card>
        <el-card>
            <div style="font-weight: bold;font-size: 15px;">收货人信息</div>
            <el-row style="margin-top: 10px">
                <el-col :span="5">{{ account.name }}</el-col>
                <el-col :span="11">{{ account.address }}</el-col>
                <el-col :span="3">{{ account.phone }}</el-col>
                <el-col :span="5">
                    <el-button type="primary" plain
                               style="float: right;margin-right: 20px"
                               size="mini"
                               @click="showEditAddressDialog"
                    >编辑收货地址
                    </el-button>

                    <el-dialog
                            title="修改地址信息"
                            :visible.sync="editAddressDialog"

                            width="30%">

                        <el-form ref="editForm" label-width="80px">
                            <el-form-item label="姓名">
                                <el-input placeholder="请填写姓名" v-model="newName"></el-input>
                            </el-form-item>

                            <el-form-item label="收货地址">
                                <el-input placeholder="请填写收货地址" v-model="newAddress"></el-input>
                            </el-form-item>

                            <el-form-item prop="newPhone" label="联系方式">
                                <el-input placeholder="请填写联系方式" v-model="newPhone"></el-input>
                            </el-form-item>
                        </el-form>

                        <span slot="footer" class="dialog-footer">
                        <el-button @click="editAddressDialog = false">取 消</el-button>
                        <el-button type="primary" @click="updateAddress">确 定</el-button>
                        </span>
                    </el-dialog>
                </el-col>
            </el-row>
        </el-card>


        <el-card>
            <span style="font-weight: bold;font-size: 15px">支付方式</span>
            <el-tag style="margin-left: 20px" type="success" plain size="medium">在线支付</el-tag>
        </el-card>

        <el-card style="width: 100%; ">

            <div slot="header" class="clearfix">
                <span style="font-weight: bold;font-size: 15px">送货清单</span>
            </div>
            <template>
                <el-table
                        height="380"
                        :header-cell-style="{fontSize: '14px','text-align':'center'}"
                        :cell-style="{'text-align':'center'}"
                        :data="carts"
                        stripe
                        style="width: 100%">
                    <el-table-column width="85" label="序号" type="index" align="center"></el-table-column>

                    <el-table-column label="图片" width="150px">
                        <template slot-scope="scope">
                            <el-avatar shape="square" :size="80" fit="fill" :src="scope.row.product.image"></el-avatar>
                        </template>
                    </el-table-column>

                    <el-table-column prop="product.name" label="商品名称" show-overflow-tooltip></el-table-column>
                    <el-table-column prop="product.price" label="单价(元)" show-overflow-tooltip></el-table-column>

                    <el-table-column label="数量">
                        <template slot-scope="scope">
                            <span style="color: #3cb8ff">{{ scope.row.quantity }}</span>
                        </template>
                    </el-table-column>

                    <el-table-column label="小计" show-overflow-tooltip>
                        <template slot-scope="scope">
                            <span style="font-size: 15px;color: #ff0024">￥{{ scope.row.total }}</span>
                        </template>
                    </el-table-column>

                </el-table>
            </template>
        </el-card>


        <el-card>
            <el-row :gutter="10">
                <el-col :span="12"><span>商品总价（包邮）：</span><span
                        style="font-size: 25px;color: #ff0024">￥{{ totalPrice }}</span></el-col>
                <el-col :span="12">
                    <el-button type="danger" @click="createOrders" size="medium" style="float: right">提交订单
                    </el-button>

                    <el-dialog
                            title="购买提示"
                            :visible.sync="dialogVisible_Pay"
                            width="30%"
                    >
                        <span>您是否通过支付宝支付完成该订单呢？</span>
                        <span slot="footer" class="dialog-footer">
                                    <el-button @click="dialogVisible_Pay = false">取 消</el-button>
                                    <el-button type="primary" @click="toMyOrders">确 定</el-button>
                                </span>
                    </el-dialog>
                </el-col>
            </el-row>
        </el-card>

    </div>
</template>

<script>
import {defineComponent} from 'vue'

export default defineComponent({
    name: "CheckoutPage",
    data() {
        // 手机号验证
        const validatePhone = (rule, value, callback) => {
            if (this.newPhone === "") {
                callback(new Error("请输入手机号"));
                console.log(value)
            } else {
                if (!/^1[3456789]\d{9}$/.test(this.newPhone)) {
                    callback(new Error("请输入正确的手机号"));
                    console.log(value)
                } else {
                    callback();
                }
            }
        };
        return {
            editAddressDialog: false,
            userId: '',
            totalPrice: 0,          // 商品总价
            newName: '',
            newAddress: '',
            newPhone: '',

            account: {},

            cartIds: [],
            productIds: [],
            carts: [],
            dialogVisible_Pay: false,


            ordersId: '',
            no: '',


            rules: {
                newPhone: [
                    {required: true, validator: validatePhone, message: '请输入正确手机号', trigger: "change"}
                ],
            }

        }
    },
    mounted() {


        if (this.$route.params.num === '' || this.$route.params.num === undefined || this.$route.params.num.length === 0) {
            this.goBack()
        }
        // 获取用户ID
        let account = JSON.parse(localStorage.getItem('account'))
        this.account = account
        this.userId = account.id
        this.cartIds = this.$route.params.num

        // 获取购物车信息
        this.getCarts()
    },

    methods: {


        toMyOrders() {
            this.$router.push('/myOrders')
        },

        goBack() {
            this.$router.go(-1)
        },

        // 移除表单的校验
        clearcheck(formName) {
            if (this.$refs[formName]) {
                this.$refs[formName].clearValidate()
            }
        },

        toMyCarts() {
            this.$router.push('/myCarts')
        },

        getCarts() {
            if (this.cartIds.length === 0) {
                this.$router.push(this.$route.matched[0].path)
                return
            }

            this.$request.post('/cart/selectByIds', this.cartIds).then(res => {
                if (res.code === '200') {
                    this.carts = res.data
                    // 更新总价
                    for (let i = 0; i < this.carts.length; i++) {
                        this.totalPrice += this.carts[i].total
                        this.productIds[i] = this.carts[i].product.id
                    }
                    this.totalPrice = parseFloat(this.totalPrice).toFixed(2)
                } else {
                    this.$message.error(res.msg)
                }

            })
        },

        /*        getProducts() {
                    this.$request.post('/cart/getCartProductsByIds', this.cartIds).then(res => {
                        if (res.code === '200') {
                            this.products = res.data
                            // console.log(this.products)
                        } else {
                            this.$message.error(res.msg)
                        }
                    })
                },*/

        createOrders() {
            // 提交订单得判断用户的地址是否存在，不存在，不可创建
            if (this.account.address === null || this.account.address === '' || this.account.address === undefined) {
                this.$message
                    .error('请先添加收货地址')
                return
            }
            if (this.account.name === null || this.account.name === '' || this.account.name === undefined) {
                this.$message
                    .error('请先设置收获人')
                return
            }
            if (this.account.phone === null || this.account.phone === '' || this.account.phone === undefined) {
                this.$message
                    .error('请先添加联系方式')
                return
            }
            this.$request.post('/orders/createOrders', {
                userId: this.userId,
                carts: this.carts,
                totalPrice: this.totalPrice,
            }).then(res => {
                if (res.code === '200') {
                    this.no = res.data
                    this.toPay()
                } else {
                    this.$message.error(res.msg)
                }
            })


            // this.$router.push('/myOrders')
        },

        toPay() {
            // const url = `http://localhost:9090/alipay/pay?subject=${'并州电子数码'}&traceNo=${this.no}&totalAmount=${this.totalPrice}`
            const url = this.$baseUrl + `/alipay/pay?subject=${'并州电子数码'}&traceNo=${this.no}&totalAmount=${this.totalPrice}`
            window.open(url, '_blank')

            this.dialogVisible_Pay = true
        },

        showEditAddressDialog() {
            this.clearcheck('editForm')
            this.editAddressDialog = true
            this.newName = JSON.parse(JSON.stringify(this.account.name))
            this.newAddress = JSON.parse(JSON.stringify(this.account.address))
            this.newPhone = JSON.parse(JSON.stringify(this.account.phone))
        },

        updateAddress() {
            if (this.newName === '' || this.newAddress === '' || this.newPhone === '') {
                this.$message.error('不能为空')
                this.editAddressDialog = false
                return
            }
            // 手机号校验
            if (this.newPhone === "") {
                this.$message.info("请输入手机号");
            } else {
                if (!/^1[3456789]\d{9}$/.test(this.newPhone)) {
                    this.$message.info("请输入正确的手机号");
                    return;
                }
            }

            this.$request.post('/user/updateNameAndAddressAndPhoneById' + '?id=' + this.account.id
                + '&name=' + this.newName
                + '&address=' + this.newAddress
                + '&phone=' + this.newPhone).then(res => {
                if (res.code === '200') {
                    this.$message.success('修改成功')
                    this.account.name = this.newName
                    this.account.address = this.newAddress
                    this.account.phone = this.newPhone
                    this.newName = ''
                    this.newAddress = ''
                    this.newPhone = ''
                    console.log(this.account)
                    // 更新本地的用户信息
                    let account = JSON.stringify(this.account)
                    localStorage.setItem('account', account)
                    // console.log(account)
                    this.editAddressDialog = false
                } else {
                    this.$message.error(res.msg)
                }
            })
        },

        updateLocalStorageMessage() {
            this.$request.post('/user/getUserById' + '?id=' + this.account.id).then(res => {
                if (res.code === '200') {
                    localStorage.setItem('account', JSON.stringify(res.data))
                    this.account =
                        JSON.parse(localStorage.getItem('account'))
                }

            })
        }

    }
})
</script>


<style>


</style>